<template>

  <div class="address-manage">
    <!-- 标题栏 -->
    <van-nav-bar :title="id ? '编辑地址' : '新增地址'" left-arrow @click-left="onClickLeft">
      <template #right>
        <van-icon name="weapp-nav" size="18" />
      </template>
    </van-nav-bar>

    <!-- 地址 -->
    <van-address-edit :area-list="areaList" :show-delete="isEditing" show-set-default show-search-result
      :search-result="searchResult" :area-columns-placeholder="['请选择', '请选择', '请选择']" @save="onSave" @delete="onDelete"
     :address-info="addressInfo" />
    

  </div>
</template>

<script setup>
import { ref, reactive,onMounted } from 'vue';
import { showToast, showConfirmDialog } from 'vant';
import { areaList } from "@vant/area-data"
import { addAddress, getAddressDetail, updateAddress, removeAddress } from '../../api/index';
import { useRoute, useRouter } from 'vue-router';
let route = useRoute();
let router = useRouter()

let id = route.query.addressId;//拿到编辑页面时传来的地址id

let isEditing = ref(false) //判断是新增还是编辑

let addressInfo = reactive({}) //默认回显信息

const searchResult = ref([]);

if (id) {
  isEditing.value = true;
} else {
  isEditing.value = false;
}

// 获取地址编码
const getAreaCode = area => {
  area = area.replace(/区|县/, "");
  for (let k in areaList.county_list) {
    if (areaList.county_list[k].includes(area)) {
      return k;
    }
  }
}


onMounted(() => {
  if (id) {
    // 进到这里说明是编辑地址
    // 先让数据回显到界面上
    getAddressDetail(id).then(res => {
      let { resultCode, data } = res;
      
      if (resultCode == 200) {
        let obj = {
          name: data.userName,
          tel: data.userPhone,
          province: data.provinceName,
          city: data.cityName,
          county: data.regionName,
          addressDetail: data.detailAddress,
          areaCode: getAreaCode(data.regionName),
          isDefault: data.defaultFlag,
        };
        for (let key in obj) {
          addressInfo[key] = obj[key];
        }
      }
    })
  }
})


// 保存按钮
let onSave = obj => {
  if (!id) {
    // 进到这里说明是新增地址
    // console.log(obj);//obj为收集到的表单数据proxy
    let option = {
      areaCode: obj.areaCode,
      cityName: obj.city,
      defaultFlag: obj.isDefault ? 1 : 0,
      detailAddress: obj.addressDetail,
      postalCode: '',
      provinceName: obj.province,
      regionName: obj.county,
      userName: obj.name,
      userPhone: obj.tel,
    }

    addAddress({ ...option }).then(res => {
      if (res.resultCode == 200) {
        showToast('新增成功')
        router.replace('/addressManage')
      }
    })
  } else {
    // 进到这里说明编辑地址完毕需要保存
    updateAddress({
      addressId: id,
      areaCode: getAreaCode(obj.county),
      cityName: obj.city,
      defaultFlag: obj.isDefault ? 1 : 0,
      detailAddress: obj.addressDetail,
      postalCode: '',
      provinceName: obj.province, 
      regionName: obj.county,
      userName: obj.name,
      userPhone:obj.tel,
    }).then(res => {
      if (res.resultCode == 200) {
        showToast({
          message: "♥编辑地址成功~~",
          duration:500,
        })
        setTimeout(() => {
          router.replace('/addressmanage')
        },500)
        
      }
    })
  }
  

};

// 删除按钮
let onDelete = () => {

  showConfirmDialog({
    title: '删除地址',
    message:'确认要删除该地址吗？',
    closeOnClickOverlay: true,
  })
    .then(() => {
      // on confirm
      removeAddress(id).then(res => {})
      showToast({
        message: '已删除',
        duration: 500,
      })
      setTimeout(() => {
      router.replace('./addressmanage')
    },500)
    
  })
}



// 点击顶部栏返回
let onClickLeft = () => {
  router.back()
}

</script>

<style scoped lang="less">
.van-button {
  background: red;
}
</style>